#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "message_mailbox.h"

#define LOGD(fmt, ...) printf(( fmt "\n"), ##__VA_ARGS__)

void *producter1(void *arg)
{
    uint32_t cnt = 10;
    mailbox_t *mb = (mailbox_t *)arg;

    do
    {
        // 在另一个线程或者主线程中执行发送操作
        LOGD("[thread-%lu]>>Send value: %d", pthread_self(), cnt);
        mb_send_wait(mb, cnt);
        cnt--;
        sleep(1);
    }while(cnt > 0);
}

void *producter2(void *arg)
{
    uint32_t cnt = 20;
    mailbox_t *mb = (mailbox_t *)arg;

    do
    {
        // 在另一个线程或者主线程中执行发送操作
        LOGD("[thread-%lu]>>Send value: %d", pthread_self(), cnt);
        mb_send_wait(mb, cnt);
        cnt--;
        sleep(1);
    }while(cnt > 10);
}

void *consumer(void *arg)
{
    mailbox_t *mb = (mailbox_t *)arg;

    while (1)
    {
        // 在当前线程或另一个线程中执行接收操作
        uint32_t value;
        mb_recv_wait(mb, &value);
        LOGD("[thread-%lu]<<Received value: %d", pthread_self(), value);
    }
}

int main(int argc, char argv[])
{
    mailbox_t mb;
    mb_init(&mb, 10);
 
    pthread_t producter_tid_1;
    pthread_t producter_tid_2;
    pthread_t consumer_tid;

    pthread_create(&producter_tid_1, NULL, producter1, (void *)&mb);
    pthread_create(&producter_tid_2, NULL, producter2, (void *)&mb);

    pthread_create(&consumer_tid, NULL, consumer, (void *)&mb);

    pthread_join(producter_tid_1, NULL);
    pthread_join(producter_tid_2, NULL);
    pthread_join(consumer_tid, NULL);

    mb_destroy(&mb);

    return 0;
}

